package loginServlet;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.LoginSystemRemote;
import entities.Utente;

public class ServletLogIn extends HttpServlet {

	private static final long serialVersionUID = -3867365856174819553L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Utente u = checkParameters(request, response);
		drawPage(u, response, request);
	}
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Utente u = checkParameters(request, response);
		drawPage(u, response, request);
	}


	private void drawPage(Utente utente, HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		if (utente == null) {
			response.sendRedirect("/ProgettoWeb/index.html");
			return;
		} else {
			request.getSession().setAttribute("type", utente.getTipoUtente());
			request.getSession().setAttribute("id", utente.getId());
			request.getSession().setAttribute("nome", utente.getNome());
			request.getSession().setAttribute("cognome",
					utente.getCognome());
			if (utente.getTipoUtente().equals("admin")) {
				response.sendRedirect("/ProgettoWeb/Admin/Profilo.jsp");
			} else {
				response.sendRedirect("/ProgettoWeb/RegisteredUser/Profilo.jsp");
			}
		}
	}

	private Utente checkParameters(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// request.getParameterNames
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		if (email == null || email.length() <= 0 || password == null
				|| password.length() <= 0) {
			return null;
		}
		try {
			Context jndiCtx = new InitialContext();
			LoginSystemRemote loginSystemRemote = (LoginSystemRemote) jndiCtx
					.lookup("Progetto/LoginSystem/remote");

			return loginSystemRemote.getUtente(email, password);
		} catch (Exception e) {
			return null;
		}
	}
}